package io.adrainty.bolee.framework.gateway.filter;

import io.adrainty.bolee.framework.gateway.utils.RequestHelper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * BaseFilter
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/7/27 下午10:49
 */
public abstract class BaseFilter implements GlobalFilter, Ordered {

    private final AntPathMatcher pathMatcher;

    protected BaseFilter() {
        this.pathMatcher = new AntPathMatcher();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        MediaType mediaType = exchange.getRequest().getHeaders().getContentType();

        boolean isUploadRequest = RequestHelper.isUploadFileRequest(mediaType);
        String path = exchange.getRequest().getURI().getPath();
        if (!isFilter(path, isUploadRequest, exchange.getRequest())) return chain.filter(exchange);
        return doFilter(exchange, chain);
    }

    /**
     * 执行过滤
     * @param exchange exchange
     * @param chain chain
     * @return Mono<Void>
     */
    protected abstract Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain);

    /**
     * 是否过滤
     *
     * @param path            请求路径
     * @param isUploadRequest 是否上传文件
     * @param request         请求
     * @return 是否过滤
     */
    protected abstract boolean isFilter(String path, boolean isUploadRequest, ServerHttpRequest request);

    protected final boolean isPathMatch(String pattern, String path) {
        return pathMatcher.match(pattern, path);
    }

    protected final boolean anyPathMatch(List<String> patternList, String path) {
        return patternList.stream().anyMatch(pattern -> isPathMatch(pattern, path));
    }

    protected final boolean nonePathMatch(List<String> patternList, String path) {
        return patternList.stream().noneMatch(pattern -> isPathMatch(pattern, path));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}
